<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'

// 聊天记录数据
const messages = ref([
  {
    id: 1,
    content: '你好！我是AI小助手，请问有什么可以帮助你的吗？',
    sender: 'ai',
    timestamp: new Date().toLocaleTimeString()
  }
])

// 用户输入内容
const inputMessage = ref('')

// 聊天室ID
const chatRoomId = ref(0)

// 是否正在发送消息
const isSending = ref(false)

// 生成聊天室ID
const generateChatRoomId = () => {
  // 从localStorage获取聊天室ID，如果没有则生成新的
  const storedId = localStorage.getItem('chatRoomId')
  if (storedId) {
    chatRoomId.value = parseInt(storedId)
  } else {
    chatRoomId.value = Math.floor(Math.random() * 1000000)
    localStorage.setItem('chatRoomId', chatRoomId.value.toString())
  }
}

// 发送消息到后端
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isSending.value) {
    return
  }

  // 添加用户消息到聊天记录
  const userMessage = {
    id: Date.now(),
    content: inputMessage.value.trim(),
    sender: 'user',
    timestamp: new Date().toLocaleTimeString()
  }
  messages.value.push(userMessage)
  inputMessage.value = ''

  // 滚动到最新消息
  await nextTick()
  scrollToBottom()

  isSending.value = true

  try {
    // 使用SSE连接调用chat接口
    const url = `http://localhost:8081/api/ai/chat?memoryId=${chatRoomId.value}&message=${encodeURIComponent(userMessage.content)}`
    const eventSource = new EventSource(url)

    let aiMessageContent = ''
    let aiMessageId = Date.now() + 1
    
    // 初始化AI消息
    const aiMessage = {
      id: aiMessageId,
      content: '',
      sender: 'ai',
      timestamp: new Date().toLocaleTimeString()
    }
    messages.value.push(aiMessage)

    // 处理接收到的消息块
    eventSource.onmessage = (event) => {
      aiMessageContent += event.data
      // 更新AI消息内容
      const index = messages.value.findIndex(msg => msg.id === aiMessageId)
      if (index !== -1) {
        messages.value[index].content = aiMessageContent
        nextTick().then(() => scrollToBottom())
      }
    }

    // 处理错误
    eventSource.onerror = (error) => {
      console.error('SSE Error:', error)
      eventSource.close()
      isSending.value = false
    }

    // 处理连接关闭
    eventSource.onclose = () => {
      console.log('SSE Connection Closed')
      isSending.value = false
    }

  } catch (error) {
    console.error('Error sending message:', error)
    isSending.value = false
  }
}

// 滚动到最新消息
const scrollToBottom = () => {
  const chatContainer = document.getElementById('chat-container')
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight
  }
}

// 处理键盘事件
const handleKeyPress = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 页面加载时生成聊天室ID
onMounted(() => {
  generateChatRoomId()
  scrollToBottom()
})
</script>

<template>
  <div class="chat-app">
    <div class="chat-header">
      <h1>AI小助手</h1>
      <div class="chat-room-info">
        聊天室ID: {{ chatRoomId }}
      </div>
    </div>
    
    <div id="chat-container" class="chat-container">
      <div v-for="message in messages" :key="message.id" :class="['message', message.sender]">
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ message.timestamp }}</div>
        </div>
        <div class="message-avatar">{{ message.sender === 'user' ? '我' : 'AI' }}</div>
      </div>
      
      <div v-if="isSending" class="typing-indicator">
        <div class="typing-dots">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    
    <div class="chat-input-area">
      <textarea
        v-model="inputMessage"
        @keydown="handleKeyPress"
        placeholder="请输入您的问题..."
        :disabled="isSending"
        rows="3"
      ></textarea>
      <button @click="sendMessage" :disabled="isSending || !inputMessage.trim()">
        {{ isSending ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.chat-app {
  display: flex;
  flex-direction: column;
  height: 90vh;
  width: 100%;
  background-color: #f5f5f5;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-header {
  background-color: #4a6fa5;
  color: white;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  margin: 0;
  font-size: 1.5rem;
}

.chat-room-info {
  font-size: 0.9rem;
  opacity: 0.9;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.chat-container::-webkit-scrollbar {
  display: none;
}

.message {
  display: flex;
  align-items: flex-end;
  max-width: 70%;
  animation: fadeIn 0.3s ease-in-out;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.ai {
  align-self: flex-start;
}

.message-content {
  background-color: #ffffff;
  padding: 0.75rem 1rem;
  border-radius: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message.user .message-content {
  background-color: #4a6fa5;
  color: white;
}

.message-text {
  word-wrap: break-word;
  line-height: 1.5;
}

.message-time {
  font-size: 0.75rem;
  opacity: 0.7;
  margin-top: 0.25rem;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 0.5rem;
  font-size: 0.85rem;
  color: #666;
}

.message.user .message-avatar {
  background-color: #4a6fa5;
  color: white;
}

.typing-indicator {
  align-self: flex-start;
  margin-left: 3rem;
}

.typing-dots {
  display: flex;
  gap: 0.3rem;
}

.typing-dots span {
  width: 8px;
  height: 8px;
  background-color: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

.chat-input-area {
  padding: 1rem;
  padding-bottom: 2rem;
  background-color: white;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 1rem;
  align-items: flex-end;
}

.chat-input-area textarea {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 1rem;
}

.chat-input-area textarea:focus {
  outline: none;
  border-color: #4a6fa5;
}

.chat-input-area button {
  padding: 0.75rem 1.5rem;
  background-color: #4a6fa5;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
  white-space: nowrap;
}

.chat-input-area button:hover:not(:disabled) {
  background-color: #3a5a85;
}

.chat-input-area button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-app {
    max-width: 100%;
    height: 100vh;
  }
  
  .message {
    max-width: 85%;
  }
  
  .chat-header {
    padding: 0.75rem 1rem;
  }
  
  .chat-header h1 {
    font-size: 1.25rem;
  }
}
</style>
